package com.alan.libapi.api.Impl;

import com.alan.libapi.utils.ConvertUtil;
/**
 * @className: PackageHeader
 * @describtion: PackageHeader
 * @author: AlanWang
 * @email: 850267876@qq.com
 * @time: 2016/4/28 09:56
 */
public class PackageHeader {
	
	public static final byte[] packHeaderBuf = {
		(byte) 0x06,(byte) 0xA1,(byte) 0x00,(byte) 0x00,
		(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00,
		(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00,
		(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00,
	};
	public static final int HEADER_LENGTH = packHeaderBuf.length;

	/**
	 * 根据内容数据长度封装协议头
	 * @param contentLength
	 * @return
	 */
	public static byte[] getHeaderBytes(int contentLength) {
		byte[] buf = packHeaderBuf.clone();
		byte[] lengthBytes = ConvertUtil.toBigEndianBytes(contentLength);
		System.arraycopy(lengthBytes, 0, buf, buf.length - lengthBytes.length, lengthBytes.length);
		return buf;
	}

	/**
	 * 根据协议头获取内容数据的长度
	 * @param headerBytes
	 * @return
	 */
	public static int getContentLength(byte[] headerBytes) {
		if(headerBytes.length < packHeaderBuf.length) {
			return 0;
		}
		byte[] lengthBytes = new byte[4];
		System.arraycopy(headerBytes, headerBytes.length - lengthBytes.length, lengthBytes, 0, lengthBytes.length);
		return ConvertUtil.getIntegerFromBigEndianBytes(lengthBytes);
	}
}
